package com.infosys.newSimpleInvertedIndex.helper;

import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

public class FileHelper {
    private FileHelper(){

    }

    public static String uploadFile(MultipartFile fileToUpload, String uploadType){
        if (fileToUpload == null) {
            return null;
        }
        try {
            String fileName = fileToUpload.getOriginalFilename();
            String filePath = "D:/upload/" + uploadType + "/" + fileName;
            fileToUpload.transferTo(new File(filePath));
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Resource downloadFile(String filePath){
        Path targetPath = Paths.get(filePath);
        // try to get resource from the path
        try {
            Resource resource = new UrlResource(targetPath.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                return null;
            }
        } catch (MalformedURLException malFormUrlExp){
            malFormUrlExp.printStackTrace();
            return null;
        }
    }
}
